<template>
  <!-- 会议底部功能控制按钮 -->
  <div class="meeting_control_box">
    <div class="control_time" v-if="!isPhone">{{times}}</div>
    <ul class="btn_ul">
      <li v-for="(item, index) in btnArr" :key="index">
        <el-badge
          :value="msgBadgeVal"
          :max="99"
          v-if="item.showBadge"
          :hidden='msgBadgeVal==0'
        >
          <img
            :src="item.url"
            alt=""
            :data-src="item.exUrl"
            class="control_img"
            :ref="`controlImg${index}`"
            @click="exchangeImg($event, item.functionname);doFunc(item.functionname)"
          >
          <p @click="clickP($event, item.functionname);doFunc(item.functionname)">{{item.title}}</p>
        </el-badge>
        <div class="btn_box" v-else>
          <div class="btn_l">
            <img
              :src="item.url"
              alt=""
              :data-src="item.exUrl"
              class="control_img"
              :ref="`controlImg${index}`"
              @click="exchangeImg($event, item.functionname);doFunc(item.functionname)"
            >
            <p @click="clickP($event, item.functionname);doFunc(item.functionname)">{{item.title}}</p>
          </div>
          <div class="btn_r" v-if="!isPhone && item.select">
            <img
              :class="{'fz':videoDeviceListStatus}"
              @click="videoDeviceListStatus=!videoDeviceListStatus"
              src="../../assets/img/select_logo.png"
              alt=""
            >
            <!-- 摄像头列表 -->
            <ul class="device_list_ul" v-if="videoDeviceListArr.length" v-show="videoDeviceListStatus">
              <li
                v-for="item in videoDeviceListArr"
                :key="item.deviceId"
                @click="chooseDevice(item)"
              >
                <span>{{item.label}}</span>
                <img v-if="deviceIndex==item.deviceId" src="../../assets/img/duihao.png" alt="">
              </li>
            </ul>
            <div class="device_list_ul no_device" v-else v-show="videoDeviceListStatus">暂无可切换的摄像头</div>
          </div>
        </div>
      </li>
    </ul>
    <div class="hunup_btn">
      <button @click="exitMeeting">{{exitBtn}}</button>
    </div>
    <mask-slot @closeMask="shareMaskStatus=false" v-show="shareMaskStatus">
      <share :url="qrcodeUrl"></share>
    </mask-slot>
    <mask-slot @closeMask='closeSupportMask' v-show="!supportMaskStatus">
      <support :url="defaultQrcodeUrl"></support>
    </mask-slot>
    <!-- 摄像头列表 -->
    <mask-slot @closeMask="isShowCameraList=false" v-show="isShowCameraList">
      <ul class="device_list_ul" v-if="videoDeviceListArr.length">
        <li
          v-for="(item, index) in videoDeviceListArr"
          :key="item.deviceId"
          @click="chooseDevice(item)"
        >
          <span v-if="item.label">{{item.label}}</span>
          <span v-else>摄像头{{index+1}}</span>
          <img v-if="deviceIndex==item.deviceId" src="../../assets/img/black_duihao.png" alt="">
        </li>
      </ul>
      <div class="device_list_ul no_device" v-else>暂无可切换的摄像头</div>
    </mask-slot>
  </div>
</template>

<script>
import vueQr from 'vue-qr'
import maskSlot from '../common/mask.vue'
import share from '../shareSlot/index.vue'
import support from '../notSupport/index.vue'

export default {
  name: "meeting_control",
  data() {
    return {
      btnArr: [
        {
          url: require('../../assets/img/qrcode.png'),
          exUrl: require('../../assets/img/qrcode.png'),
          title: '分享',
          functionname: 'qrcode'
        },
        {
          url: require('../../assets/img/start_audio.png'),
          exUrl: require('../../assets/img/ban_audio.png'),
          title: '静音',
          functionname: 'audio'
        },
        {
          url: require('../../assets/img/start_voice.png'),
          exUrl: require('../../assets/img/ban_voice.png'),
          title: '扬声器',
          functionname: 'voice'
        },
        {
          url: require('../../assets/img/start_video.png'),
          exUrl: require('../../assets/img/ban_video.png'),
          title: '摄像头',
          functionname: 'video',
          select: 'camera'
        },
        {
          url: require('../../assets/img/start_share.png'),
          exUrl: require('../../assets/img/ban_share.png'),
          title: '共享桌面',
          functionname: 'share'
        },
        {
          url: require('../../assets/img/message.png'),
          exUrl: require('../../assets/img/message.png'),
          title: '消息',
          functionname: 'message',
          showBadge: true
        },
        {
          url: require('../../assets/img/member.png'),
          exUrl: require('../../assets/img/member.png'),
          title: '成员',
          functionname: 'member'
        },
        {
          url: require('../../assets/img/range_view.png'),
          exUrl: require('../../assets/img/speech_view.png'),
          title: '视图',
          functionname: 'rangeView'
        },
        {
          url: require('../../assets/img/start_fullscreen.png'),
          exUrl: require('../../assets/img/ban_fullscreen.png'),
          title: '全屏',
          functionname: 'fullscreen'
        }
      ],
      audioStatus: false, // 麦克风
      voiceStatus: true, // 扬声器
      videoStatus: false, // 摄像头
      screenStatus: true, // 分享屏幕
      fullScreenStatus: false,
      defaultQrcodeUrl: location.href,
      qrcodeUrl: this.handleUrl(location.href),
      controlClickStatus: false,
      isPhone: navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i),
      timer: null,
      times: '00:00:00',
      t: 0,
      exitBtn: '退出会议',
      shareMaskStatus: false,
      supportMaskStatus: false,
      msgBadgeVal: 0, // 消息红泡数
      isShowMsgList: false,
      videoDeviceListArr: [],
      videoDeviceListStatus: false,
      deviceIndex: -1,
      isShowCameraList: false
    }
  },

  props: {  
    banVideo: {
      type: Boolean,
      default: false
    },
    banShareScreen: {
      type: Boolean,
      default: false
    },
    msg: {
      type: Object
    }
  },

  computed: {
    selfID () {
      return this.$store.state.functionMap.selfID
    }
  },

  watch: {
    msg (val) {
      if (val.msgType === 'controlFunc') { // 收到了被控制设备（麦克风、扬声器等）的消息
        var tipText = '', status
        status = this[`${val.msg}Status`]
        this.doFunc(val.msg)
        if (val.msg === 'audio') {
          tipText = '你已被静音！'
          [this.btnArr[1].url, this.btnArr[1].exUrl] = [this.btnArr[1].exUrl, this.btnArr[1].url]
        } else if (val.msg === 'video') {
          tipText = '你的摄像头已被关闭！'
          [this.btnArr[3].url, this.btnArr[3].exUrl] = [this.btnArr[3].exUrl, this.btnArr[3].url]
        }
        if (!status) {
          this.$notify.warning({
            title: '警告',
            message: tipText
          })
        }
      } else if (val.msgType === 'text') { // 收到了别人发来的文字消息
        // 如果没显示消息列表，则未读数+1
        // 反之置为0
        !this.isShowMsgList ? this.msgBadgeVal++ : this.msgBadgeVal = 0
      }
    }
  },

  components: {
    vueQr,
    maskSlot,
    share,
    support
  },

  async created() {
    if (this.isPhone) {
      this.btnArr = this.btnArr.filter(
        item => item.functionname != 'share' && item.functionname != 'fullscreen'
      )
      this.exitBtn = 'X'
    }
    if (this.banVideo) [this.btnArr[3].url, this.btnArr[3].exUrl] = [this.btnArr[3].exUrl, this.btnArr[3].url]
    if (this.banShareScreen) [this.btnArr[4].url, this.btnArr[4].exUrl] = [this.btnArr[4].exUrl, this.btnArr[4].url]
  },

  methods: {
    /** 获取设备列表 */
    getDeviceIDList () {
      navigator.mediaDevices.enumerateDevices().then(devices => {
        this.videoDeviceListArr = devices.filter(item => item.kind === 'videoinput')
        this.deviceIndex = this.videoDeviceListArr[0].deviceId
        console.log('video list----', this.videoDeviceListArr)
      })
    },
    /** 选择摄像头设备 */
    chooseDevice (item) {
      this.deviceIndex = item.deviceId
      this.$emit('chooseVideo', item)
    },
    /** 切换摄像头 */
    switchDevice () {
      let _device = this.videoDeviceListArr[0]
      if (this.videoDeviceListArr.length <= 2) {
        _device = this.videoDeviceListArr.find(v => v.deviceId !== this.deviceIndex)
        this.deviceIndex = _device.deviceId
        this.$emit('chooseVideo', _device)
      } else {
        this.isShowCameraList = true
      }
    },
    /** 处理url，去掉生成分享码的n参数 */
    handleUrl (url) {
      let { n=null } = this.$route.query
      if (n) {
        let _n = `&n=${n}`
        return decodeURIComponent(url).replace(_n, '')
      }
      return url
    },
    /** 父组件调用此方法 */
    handleParentDoFunc () {
      this.watchStopScreen()
      this.watchRemoteAdd()
      this.watchLocalMediaAdd()
      this.doTimer()
    },
    /** 供父组件还原该组件的一些状态 */
    handleParentResetStatus () {
      this.isShowMsgList = false
    },
    /** 判断浏览器是否支持 */
    async handleSupportStatus () {
      this.supportMaskStatus = await this.$store.dispatch('isSupports')
      return this.supportMaskStatus
    },
    /** 关闭是否支持弹窗 */
    closeSupportMask () {
      this.$router.replace({name: 'roomindex'})
    },
    /** 会议开始计时 */
    doTimer () {
      this.timer = setInterval(() => {
        this.t++
        this.goTime(this.t)
      }, 1000)
    },
    /** 复制链接 */
    copyLink () {
      var type = '', msgText = ''
      this.$copyText(location.href).then(function (e) {
        type = 'success'
        msgText = '复制成功！'
      }, function (e) {
        type = 'error',
        msgText = '复制失败！'
      })
      setTimeout(() => {
        this.$notify({
          title: '提示',
          type: type,
          message: msgText
        })
      }, 0);
    },
    goTime (t) {
      var hour = Math.floor(t / 60 / 60)
      var minute = Math.floor(t / 60 % 60)
      var second = Math.floor(t % 60)
      if (hour < 10) {
        hour = `00${hour}`.slice(-2)
      }
      if (minute < 10) {
        minute = `00${minute}`.slice(-2)
      }
      if (second < 10) {
        second = `00${second}`.slice(-2)
      }
      this.times = hour + ':' + minute + ':' + second
      t = t + 1
    },
    /** 点击文字 */
    clickP (e, name) {
      e.target.nodeName == 'P' && this.exchangeImg(e.currentTarget.previousElementSibling, name)
    },
    /** 更换图片 */
    exchangeImg(e, name) {
      if ((this.banVideo && name == 'video') || (this.banShareScreen && name == 'share')) return false
      if (!this.screenStatus && name == 'share') return false

      let src = e.src || e.target.src
      let datasrc = e.src ? e.getAttribute('data-src') : e.target.getAttribute('data-src')
      e.src ? e.src = datasrc : e.target.src = datasrc
      e.src ? e.setAttribute('data-src', src) : e.target.setAttribute('data-src', src)
    },
    /** 执行功能 */
    doFunc (functionname) {
      this[`change${functionname}`]()
    },
    /** 分享 */
    changeqrcode () {
      this.shareMaskStatus = true
    },
    /** 控制麦克风 */
    changeaudio () {
      this.umvideo.setMediaEnable(this.umvideo.mediaType.audio, this.audioStatus)
      this.audioStatus = !this.audioStatus
    },
    /** 控制扬声器 */
    changevoice () {
      this.umvideo.setSpeakerMuted(this.voiceStatus)
      this.voiceStatus = !this.voiceStatus
    },
    /** 控制摄像头 */
    changevideo () {
      if (this.banVideo) {
        this.$notify.error({
          title: '提示',
          message: '语音会议中不允许开启摄像头！'
        })
        return false
      }
      this.umvideo.setMediaEnable(this.umvideo.mediaType.video, this.videoStatus)
      this.videoStatus = !this.videoStatus
    },
    /** 控制屏幕分享 */
    async changeshare () {
      if (this.banShareScreen) {
        this.$notify.error({
          title: '提示',
          message: '语音会议中不支持屏幕分享！'
        })
        return false
      }
      try {
        await this.umvideo.setMediaEnable(this.umvideo.mediaType.screen, this.screenStatus)
      } catch (error) {
        this.$notify.error({
          title: '提示',
          message: '请选择要分享的内容！'
        })
        this.screenStatus = true
        this.changeShareImg()
      }
    },
    /** 成员列表 */
    changemember () {
      this.$emit('showFr', 'member')
    },
    /** 消息列表 */
    changemessage () {
      this.isShowMsgList = !this.isShowMsgList
      this.msgBadgeVal = 0
      this.$emit('showFr', 'message')
    },
    /** 监听有人加入 */
    watchRemoteAdd () {
      this.umvideo.on(this.umvideo.EVENTS.remoteMediaAdd, e => {
        if (e) {
          if (!this.voiceStatus) this.umvideo.setSpeakerMuted(true) // 关闭扬声器以后有人加入进来再调用一次关闭扬声器方法
        }
      })
    },
    /** 监听本地加入，比如共享屏幕 */
    watchLocalMediaAdd () {
      this.umvideo.on(this.umvideo.EVENTS.localMediaAdd, e => {
        if (e) {
          if (e.getAttribute('class') === 'screenVid') this.screenStatus = !this.screenStatus
        }
      })
    },
    /** 监听停止屏幕分享 */
    watchStopScreen () {
      this.umvideo.on(this.umvideo.EVENTS.stopScreen, () => {
        this.changeShareImg()
        this.screenStatus = !this.screenStatus
      })
    },
    /** 分享屏幕交换图片 */
    changeShareImg () {
      let src = this.$refs.controlImg4[0].src
      let datasrc = this.$refs.controlImg4[0].getAttribute('data-src')
      this.$refs.controlImg4[0].src = datasrc
      this.$refs.controlImg4[0].setAttribute('data-src', src)
    },
    /** 控制全屏 */
    changefullscreen () {
      this.fullScreenStatus ? this.exitFullScreen() : this.reqFullScreen()
      this.fullScreenStatus = !this.fullScreenStatus
    },
    /** 退出会议 */
    exitMeeting () {
      this.$emit('exitMeeting')
    },
    /** 视图排列 */
    changerangeView () {
      this.$emit('changeRangeView')
    },
    /** 全屏 */
    reqFullScreen() {
      var docElm = document.documentElement;
      //W3C
      if (docElm.requestFullscreen) {
        docElm.requestFullscreen();
      }
      //FireFox
      else if (docElm.mozRequestFullScreen) {
        docElm.mozRequestFullScreen();
      }
      //Chrome等
      else if (docElm.webkitRequestFullScreen) {
        docElm.webkitRequestFullScreen();
      }
      //IE11
      else if (docElm.msRequestFullscreen) {
        document.body.msRequestFullscreen();
      }
    },
    /** 退出全屏 */
    exitFullScreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    }
  },
  beforeDestroy () {
    clearInterval(this.timer)
  }
};
</script>

<style lang="scss" scoped>
.meeting_control_box {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  .control_time {
    color: #ffffff;
  }
  .btn_ul {
    padding: 10px 0;
    width: 600px;
    display: flex;
    align-items: center;
    li {
      display: flex;
      align-items: center;
      flex: 1;
      justify-content: center;
      text-align: center;
      position: relative;
      cursor: pointer;
      font-size: 13px;
      color: #fff;
      .btn_box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .btn_r {
          margin-left: 8px;
          img {
            width: 10px;
            height: 10px;
            transition: all 0.6s;
          }
          .fz {
            transform: rotate(180deg);
          }
          .device_list_ul {
            position: absolute;
            background-color: #000;
            bottom: 50px;
            left: -82px;
            z-index: 1;
            border-radius: 5px 5px 0 0;
            padding: 5px 15px;
            li {
              width: 200px;
              color: #fff;
              padding: 10px 20px;
              display: flex;
              align-items: center;
              span {
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
              }
              img {
                width: 15px;
                height: 15px;
                margin-left: 7px;
              }
            }
          }
        }
      }
      .cl_big_qrcode {
        position: absolute;
        top: -225px;
        right: -125px;
        .qrcode_cp {
          background-color: #fff;
          color: #2e9cf1;
          margin-top: -5px;
          padding-bottom: 3px;
        }
      }
      .sanjiao_down{
        width: 0px;
        height: 0px;
        border-top: 10px solid #ffffff;
        border-right: 10px solid  rgba(0,0,0,0);
        border-bottom: 10px solid rgba(0,0,0,0);
        border-left: 10px solid  rgba(0,0,0,0);
        margin-left: 30px;
        margin-top: -1px;
      }
      .control_img {
        width: 20px;
        cursor: pointer;
      }
    }
  }
  .hunup_btn button {
    width: 100%;
    height: 30px;
    text-align: center;
    background: #F3564D;
    border-radius: 5px;
    color: #fff;
    text-align: center;
    line-height: 30px;
    padding: 0 10px;
  }
  .device_list_ul {
    background-color: #fff;
    z-index: 1;
    padding: 5px 0;
    li {
      color: #666;
      padding: 10px 0;
      display: flex;
      align-items: center;
      span {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      img {
        width: 15px;
        height: 15px;
        margin-left: 7px;
      }
    }
  }
}
</style>
